package com.gs.synedocket.model;


import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.callback.Callback;
import com.gs.synedocket.constant.DbMsg;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.model.listener.OnResultListener;
import com.gs.synedocket.util.OKHttpUtil;
import com.gs.synedocket.util.ThreadManager;

import java.lang.reflect.Type;

public class ComboModel {
    public void combo(String typeKey, final OnResultListener onResultListener, Type typeofT) {
        OKHttpUtil.getInstance().getAsync(OKHttpUtil.NET_URL + "/api/utils/combos?typeKey=" + typeKey,
                new Callback() {
                    @Override
                    public void onSuccess(Object obj) {
                        onResultListener.onSuccess(obj);
                    }

                    @Override
                    public void onFailed(Exception e) {
                        comboLocal(typeKey, onResultListener, typeofT);
//                        onResultListener.onFails(e);
                    }
                }, typeofT);
    }

    public void comboLocal(String typeKey, final OnResultListener onResultListener, Type typeofT) {
        ThreadManager.getInstance().execute(() -> {
            ApiResultData<Object> result = new ApiResultData<>();
            result.setStatus(2000);
            result.setMessage(DbMsg.QUERY_SUCCESS);
            String comboUrl = OKHttpUtil.NET_URL + "/api/utils/combos?typeKey=";
            String url = comboUrl + typeKey;
            String trucksUrl = "trucks&typeKeyId=";
            if (typeKey.startsWith(trucksUrl)) {
                String userId = url.substring(comboUrl.length() + trucksUrl.length());
                result.setData(DBApi.getInstance().queryUserTruck(userId));
            } else {
                switch (typeKey) {
                    case "sites":
                        result.setData(DBApi.getInstance().querySite());
                        break;
                    case "trucks":
                        result.setData(DBApi.getInstance().queryTruck());
                        break;
                    case "plants":
                        result.setData(DBApi.getInstance().queryPlant());
                        break;
                    case "driverJobStates":
                        result.setData(DBApi.getInstance().queryParam());
                        break;
                }
            }
            OKHttpUtil.getInstance().getHandler().post(() -> onResultListener.onSuccess(result));
        });
    }
}
